<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart" />
    <div v-if="loading" class="loading">加载中...</div>
    <div v-if="error" class="error">{{ error }}</div>
  </div>
</template>

<script setup>
import {listProducts} from "@/api/base-data-service/products.js";
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import {listOrders} from "@/api/workorder-service/orders.js";


// 定义响应式数据
const chartRef = ref(null);
const chartInstance = ref(null);
const productList = ref([]);
const loading = ref(true);
const error = ref('');
function getList() {
  loading.value = true
  listOrders().then(response => {
    console.log(response)
    productList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 获取产品数据的函数
const fetchProductData = async () => {
  loading.value = true;
  error.value = '';

  try {
    // 发送 AJAX 请求获取产品数据
    // const response = await axios.get('/workorder-service/orders/list'); // 替换为实际的API端点
    // console.log('完整API响应:', response); // 添加这行
    // console.log('响应数据:', response.data);
    // productList.value = response.data?.rows ||
    //     response.data?.data ||
    //     (Array.isArray(response.data) ? response.data : []);
    // console.log('处理后数据:', productList.value); // 添加这行
    getList();
    initChart();
  } catch (err) {
    error.value = '获取数据失败: ' + (err.message || '未知错误');
    console.error('数据获取错误:', err);
  } finally {
    loading.value = false;
  }
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  // 销毁旧图表实例（如果存在）
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }

  // 创建新图表实例
  chartInstance.value = echarts.init(chartRef.value);

  // 准备图表数据
  const prepareChartData = () => {
    if (productList.value.length === 0) {
      return {
        xAxis: { data: [] },
        series: [{ data: [] }, { data: [] }]
      };
    }

    const xData = productList.value.map(item => item.orderNumber);
    const plannedQuantity = productList.value.map(item => item.plannedQuantity);
    const actualQuantity = productList.value.map(item => item.actualQuantity);

    return {
      xAxis: { data: xData },
      series: [
        { name: '计划数量', data: plannedQuantity },
        { name: '实际数量', data: actualQuantity }
      ]
    };
  };

  // 获取图表数据
  const chartData = prepareChartData();

  // 配置图表选项
  const options = {
    title: {
      text: '产品计划数量与实际数量对比',
      subtext: '数据来源: 产品列表',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['计划数量', '实际数量'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.xAxis.data,
      axisLabel: {
        // rotate: 45, // 旋转x轴标签，避免重叠
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '计划数量',
        type: 'bar',
        barWidth: '30%',
        data: chartData.series[0].data,
        label: {  // 添加数据标签配置
          show: true,
          position: 'top', // 标签位置，可选值：'top', 'inside', 'right'等
          formatter: '{c}' // 显示原始数据值
        }
      },
      {
        name: '实际数量',
        type: 'bar',
        barWidth: '30%',
        data: chartData.series[1].data,
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        }
      }
    ]
  };

  // 设置图表选项
  chartInstance.value.setOption(options);

  // 监听窗口大小变化，重新渲染图表
  window.addEventListener('resize', () => {
    chartInstance.value.resize();
  });
};

// 组件挂载时获取数据并初始化图表
onMounted(() => {
  fetchProductData();
});

// 组件卸载时清理资源
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
    chartInstance.value = null;
  }
  window.removeEventListener('resize', () => {});
});

// 监听数据变化，重新渲染图表
watch(() => productList.value, () => {
  if (productList.value.length > 0) {
    initChart();
  }
});
</script>

<style scoped>
.chart-container {
  position: relative;
  width: 100%;
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.loading, .error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #666;
  font-size: 16px;
  z-index: 10;
}

.error {
  color: #f56c6c;
}
</style>